package com.hzlh.oss;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import junit.framework.Assert;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import sun.misc.BASE64Decoder;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.AbortMultipartUploadRequest;
import com.aliyun.oss.model.AppendObjectRequest;
import com.aliyun.oss.model.AppendObjectResult;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CompleteMultipartUploadRequest;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.DownloadFileRequest;
import com.aliyun.oss.model.DownloadFileResult;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.InitiateMultipartUploadRequest;
import com.aliyun.oss.model.InitiateMultipartUploadResult;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.ListPartsRequest;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PartETag;
import com.aliyun.oss.model.PartListing;
import com.aliyun.oss.model.PartSummary;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.SimplifiedObjectMeta;
import com.aliyun.oss.model.UploadFileRequest;
import com.aliyun.oss.model.UploadPartCopyRequest;
import com.aliyun.oss.model.UploadPartCopyResult;
import com.aliyun.oss.model.UploadPartRequest;
import com.aliyun.oss.model.UploadPartResult;
import com.hzlh.common.util.PropertiesUtil;
import com.hzlh.core.service.impl.UploadFtpService;
import com.hzlh.core.utils.DateUtils;

@SuppressWarnings("deprecation")
public class ObjectOperations {
	public static String endpoint =PropertiesUtil.getProperties("oss.properties", "oss.endpoint");
    public static String accessKeyId = PropertiesUtil.getProperties("oss.properties", "oss.accessKeyId");
    public static String accessKeySecret = PropertiesUtil.getProperties("oss.properties", "oss.accessKeySecret");
    public static String backetName = PropertiesUtil.getProperties("oss.properties", "oss.backetName");
    public static String imgURL = PropertiesUtil.getProperties("oss.properties", "oss.backetImgUrl");
    public static String httpPath = PropertiesUtil.getProperties("oss.properties", "oss.httpPath");
    public static String expireTimein = PropertiesUtil.getProperties("oss.properties", "oss.expireTime");
//	private static String endpoint ="oss-cn-hangzhou.aliyuncs.com";
//    private static String accessKeyId = "ZvbxPrsFp0Ymrbnb";
//    private static String accessKeySecret = "YzFJefjUmKOGDLP3gdtnKvAA2pWeKS";
//    private static String backetName = "iyunting";
//    private static String imgURL = "img-cn-hangzhou.aliyuncs.com";
  
	/**
	   * 上传网络流
	   * @param BucketName
	   * @param key
	   * @param content
	   */
	public static PutObjectResult upload(String BucketName,String key,InputStream  content){
		// 创建OSSClient实例
				OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
				// 上传网络流
				PutObjectResult result = ossClient.putObject(backetName, key, content);
				// 关闭client
				ossClient.shutdown();
				return result;
	}
	/**
	   * 上传本地文件
	   * @param BucketName
	   * @param key
	   * @param content
	   */
	public static PutObjectResult upload(String BucketName,String key,File content){
		// 创建OSSClient实例
				OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
				// 上传本地文件
				PutObjectResult result = ossClient.putObject(BucketName, key, content);
				// 关闭client
				ossClient.shutdown();
				return result;
	}
	
	/**
	   * 创建模拟文件夹
	   * @param BucketName
	   * @param dir
	   * 提示：
	   * 创建模拟文件夹本质上来说是创建了一个名字以“/”结尾的文件；
	   * 对于这个文件照样可以上传下载,只是控制台会对以“/”结尾的文件以文件夹的方式展示；
	   * 多级目录创建最后一级即可，比如dir1/dir2/dir3/，创建dir1/dir2/dir3/即可，dir1/、dir1/dir2/不需要创建；
	   */
	public static void createDir(String BucketName,String dir){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		ossClient.putObject(BucketName, dir, new ByteArrayInputStream(new byte[0]));
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 
	 * @param BucketName
	 * @param key
	 * 追加上传的次数没有限制，文件大小上限为5GB。更大的文件请使用分片上传；追加类型的文件(Append Object)暂时不支持copyObject操作。
	 */
	public static void append(String BucketName,String key,InputStream inputStream){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		AppendObjectRequest appendObjectRequest = new AppendObjectRequest(BucketName, 
		        key, inputStream);
		// 第一次追加
		appendObjectRequest.setPosition(0L);
		AppendObjectResult appendObjectResult = ossClient.appendObject(appendObjectRequest);
		// 第二次追加
		appendObjectRequest.setPosition(appendObjectResult.getNextPosition());
		appendObjectResult = ossClient.appendObject(appendObjectRequest);
		// 第三次追加
		appendObjectRequest.setPosition(appendObjectResult.getNextPosition());
		appendObjectResult = ossClient.appendObject(appendObjectRequest);
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 断点续传上传
	 * @param BucketName
	 * @param key
	 * @param path
	 */
	public static void uploadBreak(String BucketName,String key,String path){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		// 设置断点续传请求
		UploadFileRequest uploadFileRequest = new UploadFileRequest(BucketName, key);
		// 指定上传的本地文件
		uploadFileRequest.setUploadFile(path);
		// 指定上传并发线程数
		uploadFileRequest.setTaskNum(5);
		// 指定上传的分片大小
		uploadFileRequest.setPartSize(1 * 1024 * 1024);
		// 开启断点续传
		uploadFileRequest.setEnableCheckpoint(true);
		// 断点续传上传
		try {
			ossClient.uploadFile(uploadFileRequest);
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 分片上传
	 * @param BucketName
	 * @param key
	 * @param path
	 */
	public static void uploadMultipart(String BucketName,String key,InputStream instream){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(BucketName, key);
		InitiateMultipartUploadResult result = ossClient.initiateMultipartUpload(request);
		String uploadId = result.getUploadId();
		List<PartETag> partETags = new ArrayList<PartETag>();
		
		UploadPartRequest uploadPartRequest = new UploadPartRequest();
		uploadPartRequest.setBucketName(BucketName);
		uploadPartRequest.setKey(key);
		uploadPartRequest.setUploadId(uploadId);
		uploadPartRequest.setInputStream(instream);
		// 设置分片大小，除最后一个分片外，其它分片要大于100KB
		uploadPartRequest.setPartSize(100 * 1024);
		// 设置分片号，范围是1~10000，
		uploadPartRequest.setPartNumber(1);
		UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
		partETags.add(uploadPartResult.getPartETag());
		Collections.sort(partETags, new Comparator<PartETag>() {
		    @Override
		    public int compare(PartETag p1, PartETag p2) {
		        return p1.getPartNumber() - p2.getPartNumber();
		    }
		});
		CompleteMultipartUploadRequest completeMultipartUploadRequest = 
		        new CompleteMultipartUploadRequest(BucketName, key, uploadId, partETags);
		ossClient.completeMultipartUpload(completeMultipartUploadRequest);
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 取消分片上传事件
	 * @param BucketName
	 * @param key
	 * @param inputStream
	 * @param uploadId
	 */
	public static void uploadMultipartStop(String BucketName,String key, InputStream inputStream,String uploadId){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		
		ossClient.putObject(BucketName, key,inputStream);
		// 取消分片上传，其中uploadId来自于initiateMultipartUpload
		AbortMultipartUploadRequest abortMultipartUploadRequest = 
		        new AbortMultipartUploadRequest(BucketName, key, uploadId);
		ossClient.abortMultipartUpload(abortMultipartUploadRequest);
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 获取已上传的分片
	 * @param BucketName
	 * @param key
	 * @param uploadId
	 * @return
	 */
	public static PartListing getMultipartUpload(String BucketName,String key,String uploadId){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		// 列举已上传的分片，其中uploadId来自于initiateMultipartUpload        
		ListPartsRequest listPartsRequest = new ListPartsRequest(BucketName, key, uploadId);
		PartListing partListing = ossClient.listParts(listPartsRequest);
		for (PartSummary part : partListing.getParts()) {
		    // 分片号，上传时候指定
		    part.getPartNumber();
		    // 分片数据大小
		    part.getSize();
		    // Part的ETag
		    part.getETag();
		    // Part的最后修改上传
		    part.getLastModified();
		}
		// 关闭client
		ossClient.shutdown();
		return partListing;
	}
	/**
	 * Object是否存在
	 * @param BucketName
	 * @param key
	 * @return
	 */
	public static boolean exist(String BucketName,String key){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// Object是否存在
		boolean found = ossClient.doesObjectExist(BucketName, key);

		// 关闭client
		ossClient.shutdown();
		return found;
	}
	/**
	 * 设置Object ACL
	 * Object有四种访问权限：Default（默认），Private（私有读写）, PublicRead（公共读私有写）, PublicReadWrite（公共读写）
	 * @param BucketName
	 * @param key
	 * @param acl
	 */
	public static void setACL(String BucketName,String key,CannedAccessControlList acl){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 设置Object权限
		ossClient.setObjectAcl(BucketName, key, acl);

		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 获取文件元信息(Object Meta)
	 * @param BucketName
	 * @param key
	 * @return
	 */
	public static ObjectMetadata get(String BucketName,String key){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 获取文件的部分元信息
		SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta(BucketName, key);
		System.out.println(objectMeta.getSize());
		System.out.println(objectMeta.getETag());
		System.out.println(objectMeta.getLastModified());

		// 获取文件的全部元信息
		ObjectMetadata metadata = ossClient.getObjectMetadata(BucketName, key);
		System.out.println(metadata.getContentType());
		System.out.println(metadata.getLastModified());
		System.out.println(metadata.getObjectType());
		

		// 关闭client
		ossClient.shutdown();
		return metadata;
	}
	
	/**
	 * 获取文件元信息(Object Meta)
	 * @param BucketName
	 * @param key
	 * @return
	 */
	public static OSSObject getObject(String BucketName,String key){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 获取文件
		OSSObject obj = ossClient.getObject(BucketName, key);
		
		ossClient.shutdown();
		return obj;
	}
	
	/**
	 * 获取文件流信息
	 * @param BucketName
	 * @param key
	 * @return
	 */
	public static byte[] getBytes(String BucketName,String key){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 获取文件
		OSSObject obj = ossClient.getObject(BucketName, key);
		byte[] b = null;
		try {
			b = IOUtils.readStreamAsByteArray(obj.getObjectContent());
			if(obj.getObjectContent()!=null)
				obj.getObjectContent().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		ossClient.shutdown();
		return b;
	}
	
	/**
	 * 列出存储空间内所有文件
	 * @param BucketName
	 * @param page 
	 * @param keyName 
	 * @param type 
	 * @param max
	 * @return 
	 */
	public static ObjectListing list(String BucketName, Integer type, String keyName, Integer page){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 构造ListObjectsRequest请求
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(BucketName);
		ObjectListing listing=null;
		// 列出Object 
		if(page==null){
		if(type==null)
		 listing = ossClient.listObjects(listObjectsRequest);
		else{
			if(type==0)
				listing = ossClient.listObjects(listObjectsRequest.withPrefix(keyName));
			if(type==1)
				listing = ossClient.listObjects(listObjectsRequest.withMarker(keyName));
		}
		}else{
			if(type==null)
				 listing = ossClient.listObjects(listObjectsRequest.withMaxKeys(page));
				else{
					if(type==0)
						listing = ossClient.listObjects(listObjectsRequest.withPrefix(keyName).withMaxKeys(page));
					if(type==1)
						listing = ossClient.listObjects(listObjectsRequest.withMarker(keyName).withMaxKeys(page));
				}
		}

		// 遍历所有Object
		System.out.println("Objects:");
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
		    System.out.println(objectSummary.getKey());
		}

		// 遍历所有CommonPrefix
		System.out.println("CommonPrefixs:");
		for (String commonPrefix : listing.getCommonPrefixes()) {
		    System.out.println(commonPrefix);
		}
		return listing;
	}
	/**
	 * 删除文件
	 * 每次最多删除1000个Object
	 * @param BucketName
	 * @param keys
	 */
	public static void delete(String BucketName,List<String> keys){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		

		DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(BucketName).withKeys(keys));
		List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
		System.out.println(deletedObjects);
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 拷贝文件
	 * @param srcBucketName
	 * @param srcKey
	 * @param destBucketName
	 * @param destKey
	 */
	public static void copy(String srcBucketName,String srcKey,String destBucketName,String destKey){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 拷贝Object
		CopyObjectResult result = ossClient.copyObject(srcBucketName, srcKey, destBucketName, destKey);
		System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());

		// 关闭client
		ossClient.shutdown();
	}
	
	public static void copyPort(String sourceBucketName,String sourceKey,String targetBucketName,String targetKey){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 得到被拷贝object大小
		ObjectMetadata objectMetadata = ossClient.getObjectMetadata(sourceBucketName, sourceKey);
		long contentLength = objectMetadata.getContentLength();

		// 分片大小，10MB
		long partSize = 1024 * 1024 * 10;

		// 计算分块数目
		int partCount = (int) (contentLength / partSize);
		if (contentLength % partSize != 0) {
		    partCount++;
		}
		System.out.println("total part count:" + partCount);

		// 初始化拷贝任务
		InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(targetBucketName, targetKey);
		InitiateMultipartUploadResult initiateMultipartUploadResult = ossClient.initiateMultipartUpload(initiateMultipartUploadRequest);
		String uploadId = initiateMultipartUploadResult.getUploadId();

		// 分片拷贝
		List<PartETag> partETags = new ArrayList<PartETag>();
		for (int i = 0; i < partCount; i++) {
		     // 计算每个分块的大小
		    long skipBytes = partSize * i;
		    long size = partSize < contentLength - skipBytes ? partSize : contentLength - skipBytes;

		    // 创建UploadPartCopyRequest
		    UploadPartCopyRequest uploadPartCopyRequest = 
		        new UploadPartCopyRequest(sourceBucketName, sourceKey, targetBucketName, targetKey);
		    uploadPartCopyRequest.setUploadId(uploadId);
		    uploadPartCopyRequest.setPartSize(size);
		    uploadPartCopyRequest.setBeginIndex(skipBytes);
		    uploadPartCopyRequest.setPartNumber(i + 1);
		    UploadPartCopyResult uploadPartCopyResult = ossClient.uploadPartCopy(uploadPartCopyRequest);

		    // 将返回的PartETag保存到List中
		    partETags.add(uploadPartCopyResult.getPartETag());
		}

		// 提交分片拷贝任务
		CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(
		                    targetBucketName, targetKey, uploadId, partETags);
		ossClient.completeMultipartUpload(completeMultipartUploadRequest);
		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 下载到本地文件
	 * @param BucketName
	 * @param key
	 * @param LocalFile
	 */
	public static void down(String BucketName,String key,String LocalFile){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		File file=new File(LocalFile);
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// 下载object到文件
		ossClient.getObject(new GetObjectRequest(BucketName, key), file);

		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 断点续传下载
	 * @param BucketName
	 * @param key
	 * @param downloadFile
	 */
	public static void downBreak(String BucketName,String key,String downloadFile){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 下载请求，10个任务并发下载，启动断点续传
		DownloadFileRequest downloadFileRequest = new DownloadFileRequest(BucketName, key);
		downloadFileRequest.setDownloadFile(downloadFile);
		downloadFileRequest.setTaskNum(10);
		downloadFileRequest.setEnableCheckpoint(true);

		// 下载文件
		DownloadFileResult downloadRes = null;
		try {
			downloadRes = ossClient.downloadFile(downloadFileRequest);
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 下载成功时，会返回文件的元信息
		downloadRes.getObjectMetadata();

		// 关闭client
		ossClient.shutdown();
	}
	public static void main(String[] args) {
		File file = new File("C:\\Users\\Administrator\\Desktop\\黄露萱\\黄露萱\\1229_1.jpg");
		String bakeget = "iyunting";
		StringBuffer st = new StringBuffer(1024);
		Random random = new Random();
		st.append("云听/测试/").append(random.nextInt(100)).append(".jpg");
		PutObjectResult result = ObjectOperations.upload(bakeget, st.toString(), file);
		String imgurl ="img-cn-hangzhou.aliyuncs.com";
		
		StringBuffer ret = new StringBuffer(2048);
		ret.append("http://").append(bakeget).append(".").append(imgurl).append("/").append(URLEncoder.encode(new String(st)));
		System.out.println(result.getETag());
		System.out.println(result.getRequestId());
		System.out.println(new String(ret));
		
	}
	
	/**
	 * 获取文件上传OSS服务器后返回路径
	 * @param appType		APP应用类别
	 * @param imgUrl		文件base64编码流文件
	 * @return
	 */
	public static String uploadFileToOss(String appType,String imgUrl){
		String[] files = imgUrl.split("base64,");
		String baseFile = files[0];
		String[] baseFiles = baseFile.split(";");
		String suffixName = baseFiles[0].substring(11, baseFiles[0].length());		//后缀名
		BASE64Decoder decode = new BASE64Decoder();
		InputStream fileInputStream = null;
		try {
			byte[] oldbyte = decode.decodeBuffer(files[1]);
			fileInputStream = new ByteArrayInputStream(oldbyte);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String filePath = UploadFtpService.getUploadFullPath("");					//获取系统生成的文件存放路径
		String fileName = UploadFtpService.getfileName(suffixName, suffixName);	//获取系统生成的文件名
		StringBuffer st = new StringBuffer(1024);
		st.append(appType).append(filePath).append(fileName);
		StringBuffer ret = new StringBuffer(2048);
		ObjectOperations.upload(backetName, new String(st), fileInputStream);
		ret.append("http://").append(backetName).append(".").append(imgURL).append("/").append(URLEncoder.encode(new String(st)));
		return new String(ret);
	}
	
	/**
	 * 上传文件至阿里云OSS
	 * @param appType
	 * @param file
	 * @return
	 */
	public static String uploadLocalFileToOss(String appType,MultipartFile file){
		String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1, file.getOriginalFilename().length());		//后缀名
		InputStream fileInputStream = null;
		try {
			
			fileInputStream = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String filePath = UploadFtpService.getUploadFullPath("");					//获取系统生成的文件存放路径
		String fileName = UploadFtpService.getfileName(suffixName, suffixName);	//获取系统生成的文件名
		StringBuffer st = new StringBuffer(1024);
		st.append(appType).append(filePath).append(fileName);
		StringBuffer ret = new StringBuffer(2048);
		ObjectOperations.upload(backetName, new String(st), fileInputStream);
		ret.append("http://").append(httpPath).append("/").append(URLEncoder.encode(new String(st)));
		return new String(ret);
	}
	
	/**
	 * 后台签名阿里云OSS
	 * @param appType
	 * @param file
	 * @return
	 */
	public static String PostPolicy(String appType){
		 String host = "http://" + backetName + "." + endpoint;
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		JSONObject ja1=null;
        try { 	
        	long expireTime = Long.valueOf(expireTimein);
        	long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, appType);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);
            StringBuffer ret = new StringBuffer(2048);
    		ret.append("http://").append(httpPath).append("/");
            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessKeyId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            //respMap.put("expire", formatISO8601Date(expiration));
            respMap.put("dir", appType);
            respMap.put("host", host);
            respMap.put("cdnPath", ret.toString());
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            ja1 = JSONObject.fromObject(respMap);
            System.out.println(ja1.toString());
        } catch (Exception e) {
            Assert.fail(e.getMessage());
            e.printStackTrace();
        }
		return ja1.toString();
	}
	
	
	@SuppressWarnings("unused")
	private String getUploadFullPath(String uploadType) {
		Date today = DateUtils.getCurrentDate();

		if (StringUtils.isNotBlank(uploadType)) {
			uploadType = "/" + uploadType;
		}

		String s = uploadType
				+ "/" + DateUtils.formatDate("yyyyMM", today)
				+ "/" + DateUtils.formatDate("dd", today)
				+ "/" + DateUtils.formatDate("HH", today) + "/";
		return s;
	}
	
//	2017-03-15.上传不根据时间，修改文件名
	public static String uploadLocalFileToOss(String appType,MultipartFile file,String key){
		String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1, file.getOriginalFilename().length());		//后缀名
		InputStream fileInputStream = null;
		try {
			
			fileInputStream = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String filePath = UploadFtpService.getUploadFullPath("");					//获取系统生成的文件存放路径
		String fileName = UploadFtpService.getfileName(file.getOriginalFilename(), suffixName,key);	//获取系统生成的文件名
		StringBuffer st = new StringBuffer(1024);
		st.append(appType).append(filePath).append(fileName);
		StringBuffer ret = new StringBuffer(2048);
		ObjectOperations.upload(backetName, new String(st), fileInputStream);
		ret.append("http://").append(httpPath).append("/").append(st);
		return new String(ret);
	}
}
